package com.sina.microblog
{
	import com.adobe.serialization.json.JSON;
	import com.sina.microblog.data.MicroBlogAtUser;
	import com.sina.microblog.data.MicroBlogComment;
	import com.sina.microblog.data.MicroBlogCount;
	import com.sina.microblog.data.MicroBlogEmotion;
	import com.sina.microblog.data.MicroBlogFavorites;
	import com.sina.microblog.data.MicroBlogFavoritesTag;
	import com.sina.microblog.data.MicroBlogHotStatuses;
	import com.sina.microblog.data.MicroBlogHotTrends;
	import com.sina.microblog.data.MicroBlogInterestedUser;
	import com.sina.microblog.data.MicroBlogListVO;
	import com.sina.microblog.data.MicroBlogLocation;
	import com.sina.microblog.data.MicroBlogRateLimit;
	import com.sina.microblog.data.MicroBlogStatus;
	import com.sina.microblog.data.MicroBlogTag;
	import com.sina.microblog.data.MicroBlogTrends;
	import com.sina.microblog.data.MicroBlogUnread;
	import com.sina.microblog.data.MicroBlogUser;
	import com.sina.microblog.data.MicroBlogUsersRelationship;
	import com.sina.microblog.events.MicroBlogErrorEvent;
	import com.sina.microblog.events.MicroBlogEvent;
	import com.sina.microblog.utils.StringEncoders;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.external.ExternalInterface;
	import flash.net.LocalConnection;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.net.navigateToURL;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	import flash.utils.Endian;
	
	public class MicroBlog extends EventDispatcher
	{
		private static const MULTIPART_FORMDATA:String="multipart/form-data; boundary=";
		private static const CONTENT_DISPOSITION_BASIC:String='Content-Disposition: form-data; name="$name"';
		private static const CONTENT_TYPE_JPEG:String="Content-Type: image/pjpeg";
		private static const CONTENT_TRANSFER_ENCODING:String="Content-Transfer-Encoding: binary";	
		
		private var _consumerKey:String = "";
		private var _consumerSecret:String = "";
		private var _access_token:String = "";
		private var _expires_in:String = "";
		private var _refresh_token:String = "";
		private var _source:String = "";
		private var _pin:String="";
		private var _verifier:String = "";
		//		private var _isTrustDomain:Boolean = true;
		private var _xauthUser:String = "";
		private var _xauthPass:String = "";
		
		private var xauthLoader:URLLoader;
		
		///登录的时候临时建立的频道
		private var _localConnectionChanel:String;
		///获取anywheretoken值的连接
		private var _conn:LocalConnection;
		
		private var serviceLoader:Dictionary = new Dictionary();
		private var loaderMap:Dictionary = new Dictionary();
		
		private var _proxyURI:String;
		private var _isSecureDomain:Boolean = true;
		
		public var _testData:String;
		
		public function MicroBlog()
		{
			
		}
		
		///////////////////////////////////
		// Event Handler
		///////////////////////////////////

		/**
		 * 客户端登陆成功的事件 
		 * @param e
		 * 
		 */		
		private function xauthLoader_onComplete(e:Event):void
		{
			var result:String = xauthLoader.data as String;
			trace("xauthLoader_onComplete>"+result);
			if (result.length > 0)
			{
				_xauthPass = _xauthUser = "";
				var resultObj:Object = JSON.decode(result);
				this.access_token = resultObj["access_token"];
				this.expires_in = resultObj["expires_in"];
				this.refresh_token = resultObj["refresh_token"];	
				//				trace(access_token + "::" + expires_in + "::" + refresh_token);			
				var loginEvt:MicroBlogEvent = new MicroBlogEvent(MicroBlogEvent.LOGIN_RESULT);
				loginEvt.result = {"access_token": this.access_token, "expires_in": this.expires_in, "refresh_token": this.refresh_token};
				dispatchEvent(loginEvt);
			}
		}
		
		private function loader_onComplete(event:Event):void
		{
			var loader:URLLoader=event.target as URLLoader;
			var processor:Object=loaderMap[loader];
			var dataStr:String = loader.data as String;
			
			if ( dataStr.length  <= 0 )
			{
				var ioError:MicroBlogErrorEvent = new MicroBlogErrorEvent(MicroBlogErrorEvent.NET_WORK_ERROR);
				ioError.message = "The network error";
				dispatchEvent(ioError);
				return;
			}			
			
			_testData = dataStr;
			
			var result:Object = JSON.decode(dataStr);
			if (result["error"]  != null)
			{
				var error:MicroBlogErrorEvent = new MicroBlogErrorEvent(processor.errorEvent);
				error.message="Error " + result.error_code + " : " + result.error + ",description:" + result.error_description;
				dispatchEvent(error);
			}else{
				var e:MicroBlogEvent = new MicroBlogEvent(processor.resultEvent);
				e.result = processor.dataFunc(result);
				e.nextCursor=Number(result.next_cursor);
				e.previousCursor=Number(result.previous_cursor);
				dispatchEvent(e);
			}
		}
		
		private function loader_onError(event:IOErrorEvent):void
		{
			var loader:URLLoader=event.target as URLLoader;
			var processor:Object=loaderMap[loader];
			var error:MicroBlogErrorEvent=new MicroBlogErrorEvent(processor.errorEvent);
			error.message=event.text;
			dispatchEvent(error);
		}
		
		private function loader_onSecurityError(event:SecurityErrorEvent):void
		{
			trace("loader_onSecurityError:"+event.text);
			dispatchEvent(event);
		}
		
		private function xauthLoader_onError(evt:IOErrorEvent):void 
		{
			trace("xauthLoader_onError:"+evt.text);
			var e:MicroBlogErrorEvent = new MicroBlogErrorEvent(MicroBlogErrorEvent.LOGIN_ERROR);
			e.message = xauthLoader.data;
			dispatchEvent(e);
		}
		
		/**
		 * 使用localConnection从登陆组件传入token相关信息 
		 * @param access_token
		 * @param expires_in
		 * @param refresh_token
		 */		
		public function loginResult(access_token:String, expires_in:String, refresh_token:String):void
		{			
			//			trace(access_token + "::" + expires_in + "::" + refresh_token);	
			_access_token = access_token;
			_expires_in = expires_in;
			_refresh_token = refresh_token;
			
			var loginEvt:MicroBlogEvent = new MicroBlogEvent(MicroBlogEvent.LOGIN_RESULT);
			loginEvt.result = {"access_token": this.access_token, "expires_in": this.expires_in, "refresh_token": this.refresh_token};
			dispatchEvent(loginEvt);
		}
		
		///////////////////////////////////
		// Weibo API
		///////////////////////////////////
		/**
		 *  
		 * @param userName
		 * @param password
		 * 
		 */		
		public function login(userName:String=null, password:String=null):void
		{		
			_xauthUser = _xauthPass = "";
			if (userName != null && password != null) 
			{
				_xauthUser = userName;
				_xauthPass = password;
				if (null == xauthLoader)
				{
					xauthLoader = new URLLoader();
					xauthLoader.addEventListener(Event.COMPLETE, xauthLoader_onComplete, false, 0, true);
					xauthLoader.addEventListener(IOErrorEvent.IO_ERROR, xauthLoader_onError, false, 0, true);
					xauthLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_onSecurityError, false, 0, true);
				}		
				var xval:URLVariables = new URLVariables();
				xval.client_id = _consumerKey;
				xval.client_secret = _consumerSecret;
				xval.grant_type = "password";
				xval.username = _xauthUser;
				xval.password = _xauthPass;			
				var xurl:String = API.OAUTH_ACCESS_TOKEN_REQUEST_URL;
				var xreq:URLRequest = new URLRequest(xurl);
				xreq.method = URLRequestMethod.POST;
				xreq.data = xval;
				xauthLoader.load(xreq);
				return;
			}else{
				_localConnectionChanel = _source + Math.round(Math.random() * 1000000);	
				_conn = new LocalConnection();
				_conn.client = this;
				_conn.connect("_" + String(_localConnectionChanel));
				_conn.allowDomain("*");
				var url:String = API.OAUTH_AUTHORIZE_REQUEST_URL + "?client_id=" + _source;
				//url += "&redirect_uri=" + API.CONNECT_COMP;
				url += "&state=" + _localConnectionChanel; //登陆的频道会通过这个state传回callback.htm页面中。并使用localconnection去连接
				url += "&display=flash";	
				url += "&response_type=token";
				if (ExternalInterface.available)
				{
					try {
						ExternalInterface.call("window.open", url,'newwindow','height=353,width=570,top=0,left=0,toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no, z-look=yes, alwaysRaised=yes');
					}catch (err:Error) {
						navigateToURL(new URLRequest(url), "_blank");
					}
				}else {
					navigateToURL(new URLRequest(url), "_blank");
				}
			}
		}
		
		
		/*---------------------------- 微博读取接口 ------------------------------------*/
		/**
		 * 发布一条新微博 
		 * @param status		要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。
		 * @param pic			要上传的图片，仅支持JPEG、GIF、PNG格式，图片大小小于5M。
		 * @param picName		文件名称，带文件后缀 
		 * @param pic_url		图片的URL地址，必须以http开头。 
		 * @param lat			纬度，有效范围：-90.0到+90.0，+表示北纬，默认为0.0。
		 * @param long			经度，有效范围：-180.0到+180.0，+表示东经，默认为0.0。 
		 * @param annotations	元数据，主要是为了方便第三方应用记录一些适合于自己使用的信息，每条微博可以包含一个或者多个元数据，必须以json字串的形式提交，字串长度不超过512个字符，具体内容可以自定。
		 */		
		public function updateStatus(status:String, pic:ByteArray=null, picName:String = "", pic_url:String = "", lat:Number = NaN, long:Number = NaN, annotations:String = ""):void
		{
			var req:URLRequest;
			var params:Object = {};
			if ( status ) params.status = encodeMsg(status);			
			if (!isNaN(lat)) params.lat = lat;
			if (!isNaN(long)) params.long = long;
			if (annotations != "") params.annotations = annotations;
			var uri:String;
			if(pic != null){
				if(picName == "") picName = "pic.jpg";
				uri = API.STATUS_UPLOAD;
				addProcessor(uri, processStatus, MicroBlogEvent.UPDATE_STATUS_RESULT, MicroBlogErrorEvent.UPDATE_STATUS_ERROR);
				if(_isSecureDomain){
					req = getMicroBlogRequest(API.API_BASE_URL + uri + ".json", params, URLRequestMethod.POST);
				}else{
					req = getMicroBlogRequest(_proxyURI + "?uri=" + uri + "&method=" + URLRequestMethod.POST, params, URLRequestMethod.POST);
				}
				var boundary:String=makeBoundary();
				req.contentType = MULTIPART_FORMDATA + boundary;		
				req.data = makeMultipartPostData(boundary, "pic", picName, pic, req.data);
			}else if(pic_url != ""){
				uri = API.STATUS_UPLOAD_URL_TEXT;
				params.url = pic_url;
				if(_isSecureDomain){
					req = getMicroBlogRequest(API.API_BASE_URL + uri + ".json", params, URLRequestMethod.POST)
				}else{
					req = getMicroBlogRequest(_proxyURI + "?uri=" + uri + "&method=" + URLRequestMethod.POST, params, URLRequestMethod.POST);
				}
				addProcessor(uri, processStatus, MicroBlogEvent.UPDATE_STATUS_RESULT, MicroBlogErrorEvent.UPDATE_STATUS_ERROR);
			}else{
				uri = API.STATUS_UPDATE;
				if(_isSecureDomain){
					req = getMicroBlogRequest(API.API_BASE_URL + uri + ".json", params, URLRequestMethod.POST)
				}else{
					req = getMicroBlogRequest(_proxyURI + "?uri=" + uri + "&method=" + URLRequestMethod.POST, params, URLRequestMethod.POST);
				}
				addProcessor(uri, processStatus, MicroBlogEvent.UPDATE_STATUS_RESULT, MicroBlogErrorEvent.UPDATE_STATUS_ERROR);
			}
			executeRequest(uri, req);
		}
		//获取当前登录用户及其所关注用户的最新微博
		//feature : 0：全部、1：原创、2：图片、3：视频、4：音乐
		public function loadFriendsTimeline(sinceId:String="0",maxId:String="0",count:int=50,page:int=1,feature:int = 0 ):void{
			callWeiboAPICommon(API.FRIENDS_TIMELINE,processStatusArray,
				{since_id:sinceId,max_id:maxId,count:count,page:page,feature:feature},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FRIENDS_TIMELINE_RESULT,MicroBlogErrorEvent.LOAD_FRIENDS_TIMELINE_ERROR);
		}
		//获取用户发布的微博
		public function loadUserTimeline(userId:String,screenName:String="",sinceId:String="0",maxId:String="0",count:int=50,page:int=1,feature:int = 0 ):void{
			callWeiboAPICommon(API.USER_TIMELINE,processStatusArray,
				{uid:userId,screen_name:screenName,since_id:sinceId,max_id:maxId,count:count,page:page,feature:feature},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_USER_TIMELINE_RESULT,MicroBlogErrorEvent.LOAD_USER_TIMELINE_ERROR);
		}
		
		//根据ID获取单条微博信息
		public function loadStatus(id:String):void{
			callWeiboAPICommon(API.STATUSES_SHOW,processStatus,
				{id:id},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_STATUS_RESULT,MicroBlogErrorEvent.LOAD_STATUS_ERROR);
		}
		
		//按天返回热门转发榜
		public function loadHotRepostDaily(count:int=20):void{
			callWeiboAPICommon(API.REPOST_DAILY,processStatusArray,
				{count:count},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_HOT_REPOST_DAILY_RESULT,MicroBlogErrorEvent.LOAD_HOT_REPOST_DAILY_ERROR);
		}		
		//按周返回热门转发榜
		public function loadHotRepostWeekly(count:int=20):void{
			callWeiboAPICommon(API.REPOST_WEEKLY,processStatusArray,
				{count:count},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_HOT_REPOST_WEEKLY_RESULT,MicroBlogErrorEvent.LOAD_HOT_REPOST_WEEKLY_ERROR);
		}
		
		//按天返回热门评论榜
		public function loadHotCommentDaily(count:int=20):void{
			callWeiboAPICommon(API.COMMENTS_DAILY,processCommentArray,
				{count:count},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_HOT_COMMENT_DAILY_RESULT,MicroBlogErrorEvent.LOAD_HOT_COMMENT_DAILY_ERROR);
		}		
		//按周返回热门评论榜
		public function loadHotCommentWeekly(count:int=20):void{
			callWeiboAPICommon(API.COMMENTS_WEEKLY,processCommentArray,
				{count:count},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_HOT_COMMENT_WEEKLY_RESULT,MicroBlogErrorEvent.LOAD_HOT_COMMENT_WEEKLY_ERROR);
		}
		
		//批量获取指定微博的转发数评论数
		public function loadStatusCounts(ids:String):void{
			callWeiboAPICommon(API.STATUSES_COUNT,processStatusCount,
				{ids:ids},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_STATUS_COUNTS_RESULT,MicroBlogErrorEvent.LOAD_STATUS_COUNTS_ERROR);
		}		
		/*---------------------------- 微博写入接口 ------------------------------------*/
		//转发一条微博信息
		//isComment:0：否、1：评论给当前微博、2：评论给原微博、3：都评论，默认为0 。
		public function repostStatus(id:String,status:String,isComment:int=0):void{
			status = encodeMsg(status);
			callWeiboAPICommon(API.STATUS_REPOST,processStatus,
				{id:id,status:status,is_comment:isComment},URLRequestMethod.POST,
				MicroBlogEvent.REPOST_STATUS_RESULT,MicroBlogErrorEvent.REPOST_STATUS_ERROR);
		}
		//删除微博信息
		public function deleteStatus(id:String):void{
			callWeiboAPICommon(API.DELETE_STATUS,processStatus,
				{id:id},URLRequestMethod.POST,
				MicroBlogEvent.DELETE_STATUS_RESULT,MicroBlogErrorEvent.DELETE_STATUS_ERROR);
		}
		
		//获取官方表情
		public function emotions(type:String="face"):void{
			callWeiboAPICommon(API.EMOTIONS,processEmotions,
				{type:type},URLRequestMethod.GET,
				MicroBlogEvent.EMOTIONS_RESULT,MicroBlogErrorEvent.EMOTIONS_ERROR);
		}	
		/*---------------------------- 评论读取接口 ------------------------------------*/

		//获取某条微博的评论列表
		public function loadComments(id:String,sinceId:String="0",maxId:String="0",count:int=50,page:int=1):void{
			callWeiboAPICommon(API.COMMENTS_SHOW,processCommentArray,
				{id:id,since_id:sinceId,max_id:maxId,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_COMMENTS_RESULT,MicroBlogErrorEvent.LOAD_COMMENTS_ERROR);
		}	
		//获取当前登录用户所发出的评论列表
		public function loadCommentsByMe(sinceId:String="0",maxId:String="0",count:int=50,page:int=1):void{
			callWeiboAPICommon(API.COMMENTS_BY_ME,processCommentArray,
				{since_id:sinceId,max_id:maxId,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_COMMENTS_BY_ME_RESULT,MicroBlogErrorEvent.LOAD_COMMENTS_BY_ME_ERROR);
		}
		//获取当前登录用户所发出的评论列表
		public function loadCommentsToMe(sinceId:String="0",maxId:String="0",count:int=50,page:int=1):void{
			callWeiboAPICommon(API.COMMENTS_TO_ME,processCommentArray,
				{since_id:sinceId,max_id:maxId,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_COMMENTS_TO_ME_RESULT,MicroBlogErrorEvent.LOAD_COMMENTS_TO_ME_ERROR);
		}
		
		//获取当前登录用户的最新评论包括接收到的与发出的
		public function loadCommentsTimeline(sinceId:String="0",maxId:String="0",count:int=50,page:int=1):void{
			callWeiboAPICommon(API.COMMENTS_TIMELINE,processCommentArray,
				{since_id:sinceId,max_id:maxId,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_COMMENTS_TIMELINE_RESULT,MicroBlogErrorEvent.LOAD_COMMENTS_TIMELINE_ERROR);
		}		
		//获取最新的提到当前登录用户的评论，即@我的评论
		public function loadCommentsMentions(sinceId:String="0",maxId:String="0",count:int=50,page:int=1):void{
			callWeiboAPICommon(API.COMMENTS_MENTIONS,processCommentArray,
				{since_id:sinceId,max_id:maxId,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_COMMENTS_MENTIONS_RESULT,MicroBlogErrorEvent.LOAD_COMMENTS_MENTIONS_ERROR);
		}
		//根据评论ID批量返回评论信息
		//cids:需要查询的批量评论ID，用半角逗号分隔，最大50
		public function loadBatchComments(cids:String){
			callWeiboAPICommon(API.COMMENTS_SHOW_BATCH,processCommentsBatch,
				{cids:cids},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_BATCH_COMMENTS_RESULT,MicroBlogErrorEvent.LOAD_BATCH_COMMENTS_ERROR);
		}
		/*---------------------------- 评论写入接口 ------------------------------------*/
		//对一条微博进行评论
		//commentOri:当评论转发微博时，是否评论给原微博，0：否、1：是，默认为0。
		public function commentStatus(id:String,comment:String,commentOri:int=0):void{
			comment = encodeMsg(comment);
			callWeiboAPICommon(API.COMMENT_STATUS,processComment,
				{id:id,comment:comment,comment_ori:commentOri},URLRequestMethod.POST,
				MicroBlogEvent.COMMENT_STATUS_RESULT,MicroBlogErrorEvent.COMMENT_STATUS_ERROR);
		}
		
		//删除一条评论
		public function deleteComment(cid:String):void{
			callWeiboAPICommon(API.DELETE_COMMENT,processComment,
				{cid:cid},URLRequestMethod.POST,
				MicroBlogEvent.DELETE_COMMENT_RESULT,MicroBlogErrorEvent.DELETE_COMMENT_ERROR);
		}
		//根据评论ID批量删除评论
		public function deleteCommentBatch(ids:String):void{
			callWeiboAPICommon(API.DELETE_COMMENTS_BATCH,processGeneralApi,
				{ids:ids},URLRequestMethod.POST,
				MicroBlogEvent.DELETE_COMMENT_BATCH_RESULT,MicroBlogErrorEvent.DELETE_COMMENT_BATCH_ERROR);
		}
		//回复一条评论
		//cid:需要回复的评论ID。
		//id:需要评论的微博ID。
		//commentOri:当评论转发微博时，是否评论给原微博，0：否、1：是，默认为0。
		//withoutMention:回复中是否自动加入“回复@用户名”，0：是、1：否，默认为0。
		public function replyComment(cid:String,id:String,comment:String,commentOri:int=0,withoutMention:int=0):void{
			comment = encodeMsg(comment);
			callWeiboAPICommon(API.REPLY_COMMENT,processComment,
				{cid:cid,id:id,comment:comment,comment_ori:commentOri,without_mention:withoutMention},URLRequestMethod.POST,
				MicroBlogEvent.DELETE_COMMENT_BATCH_RESULT,MicroBlogErrorEvent.DELETE_COMMENT_BATCH_ERROR);
		}
		/*---------------------------- 用户读取接口 ------------------------------------*/
		//获取当前登录用户的UID
		public function getUID():void{
			callWeiboAPICommon(API.GET_USER_ID,processGeneralApi,
				null,URLRequestMethod.GET,
				MicroBlogEvent.VERIFY_CREDENTIALS_RESULT,MicroBlogErrorEvent.VERIFY_CREDENTIALS_ERROR);
		}		
		//查看某用户信息
		public function loadUser(userId:String):void{
			callWeiboAPICommon(API.SHOW_USER,processGeneralApi,
				{uid:userId},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_USER_INFO_RESULT,MicroBlogErrorEvent.LOAD_USER_INFO_ERROR);
		}
		//批量获取用户的粉丝数、关注数、微博数
		public function loadUserCounts(uids:String):void{
			callWeiboAPICommon(API.COUNTS_USERS,processUser,
				{uids:uids},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_USER_COUNTS_RESULT,MicroBlogErrorEvent.LOAD_USER_COUNTS_ERROR);
		}		
		/*---------------------------- 关系读取接口 ------------------------------------*/
		//获取用户的关注列表
		//count:单页返回的记录条数，默认为50，最大不超过200。
		//cursor:返回结果的游标，下一页用返回值里的next_cursor，上一页用previous_cursor，默认为0。
		public function loadFriends(uid:String,screenName:String="",count:int=50,cursor:int=0):void{
			callWeiboAPICommon(API.FRIENDS,processUserArray,
				{uid:uid,screen_name:screenName,count:count,cursor:cursor},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FRIENDS_INFO_RESULT,MicroBlogErrorEvent.LOAD_FRIENDS_INFO_ERROR);
		}
		//获取两个用户之间的共同关注人列表
		//uid:需要获取共同关注关系的用户UID。
		//suid:需要获取共同关注关系的用户UID，默认为当前登录用户。
		public function loadFriendsInCommon(uid:String,suid:String,count:int=50,page:int=1):void{
			callWeiboAPICommon(API.FRIENDS_IN_COMMON,processUserArray,
				{uid:uid,suid:suid,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FRIENDS_IN_COMMON_RESULT,MicroBlogErrorEvent.LOAD_FRIENDS_IN_COMMON_ERROR);
		}		
		//获取用户的双向关注列表，即互粉列表
		public function loadFriendsBilateral(uid:String,count:int=50,page:int=1):void{
			callWeiboAPICommon(API.FRIENDS_BILATERAL,processUserArray,
				{uid:uid,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FRIENDS_IN_COMMON_RESULT,MicroBlogErrorEvent.LOAD_FRIENDS_IN_COMMON_ERROR);
		}
		//获取用户的粉丝列表
		public function loadFollowers(uid:String,screenName:String,count:int=50,cursor:int=0):void{
			callWeiboAPICommon(API.FOLLOWERS,processUserArray,
				{uid:uid,screen_name:screenName,count:count,cursor:cursor},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FOLLOWERS_INFO_RESULT,MicroBlogErrorEvent.LOAD_FOLLOWERS_INFO_ERROR);
		}
		//获取用户的活跃粉丝列表，即优质粉丝
		public function loadFollowersActive(uid:String,count:int=20):void{
			callWeiboAPICommon(API.FOLLOWERS_ACTIVE,processUserArray,
				{uid:uid,count:count},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FOLLOWERS_ACTIVE_RESULT,MicroBlogErrorEvent.LOAD_FOLLOWERS_ACTIVE_ERROR);
		}
		//获取两个用户之间的详细关注关系情况
		//参数sourceId与sourceScreenName二者必选其一，且只能选其一
		//参数targetId与targetScreenName二者必选其一，且只能选其一
		public function loadFriendRelation(sourceId:String,targetId:String,sourceScreenName:String="",targetScreenName:String=""):void{
			callWeiboAPICommon(API.FOLLOWERS_SHOW,processRelation,
				{source_id:sourceId,source_screen_name:sourceScreenName,target_id:targetId,target_screen_name:targetScreenName},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FRIEND_RELATION_RESULT,MicroBlogErrorEvent.LOAD_FRIEND_RELATION_ERROR);
		}
		/*---------------------------- 关系写入接口 ------------------------------------*/	
		//关注某用户
		public function follow(userId:String="",screenName:String=""):void{
			var param:Object = new Object();
			if(userId){
				param.uid = userId;
			}
			if(screenName){
				param.screen_name = screenName;
			}
			callWeiboAPICommon(API.FOLLOWER,processUser,
				param,URLRequestMethod.POST,
				MicroBlogEvent.FOLLOW_RESULT,MicroBlogErrorEvent.FOLLOW_ERROR);
		}	
		//取消关注一个用户
		public function cancelfollow(userId:String="",screenName:String=""):void{
			var param:Object = new Object();
			if(userId){
				param.uid = userId;
			}
			if(screenName){
				param.screen_name = screenName;
			}			
			callWeiboAPICommon(API.CANCEL_FOLLOWER,processUser,
				param,URLRequestMethod.POST,
				MicroBlogEvent.CANCEL_FOLLOWING_RESULT,MicroBlogErrorEvent.CANCEL_FOLLOWING_ERROR);
		}
		
		/*---------------------------- 账号读取接口 ------------------------------------*/
		//获取当前用户API访问频率限制
		public function getRateLimitStatus():void{
			callWeiboAPICommon(API.RATE_LIMIT_STATUS,processRateLimit,
				null,URLRequestMethod.GET,
				MicroBlogEvent.GET_RATE_LIMIT_STATUS_RESULT,MicroBlogErrorEvent.GET_RATE_LIMIT_STATUS_ERROR);
		}
		//获取所有学校列表
		//type:学校类型，1：大学、2：高中、3：中专技校、4：初中、5：小学，默认为1。
		//capital:学校首字母，默认为A。
		//keyword:学校名称关键字。
		//count:返回的记录条数，默认为10。
		public function getSchoolList(province:String,city:String,
			area:String,type:String="1",capital:String="A",keyword:String="",count:int = 0):void{
			callWeiboAPICommon(API.SCHOOL_LIST,processGeneralApi,
				{province:province,city:city,area:area,type:type,capital:capital,keyword:keyword,count:count},URLRequestMethod.GET,
				MicroBlogEvent.GET_SCHOOL_LIST_RESULT,MicroBlogErrorEvent.GET_SCHOOL_LIST_ERROR);
		}

		/*---------------------------- 账号写入接口 ------------------------------------*/	
		//退出登录
		public function logout():void{
			callWeiboAPICommon(API.LOGOUT,processGeneralApi,
				null,URLRequestMethod.GET,
				MicroBlogEvent.LOGOUT_RESULT,MicroBlogErrorEvent.LOGOUT_ERROR);
		}
		/*---------------------------- 收藏读取接口 ------------------------------------*/
		//获取当前用户的收藏列表
		public function loadFavorites(count:int=50,page:int=1):void{
			callWeiboAPICommon(API.FAVORITES,processFavoritesArray,
				{count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FAVORITE_LIST_RESULT,MicroBlogErrorEvent.LOAD_FAVORITE_LIST_ERROR);
		}
		//获取单条收藏信息
		public function loadOneFavorites(id:String):void{
			callWeiboAPICommon(API.FAVORITE_SHOW,processFavorites,
				{id:id},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_ONE_FAVORITE_LIST_RESULT,MicroBlogErrorEvent.LOAD_ONE_FAVORITE_LIST_ERROR);
		}
		//获取当前用户某个标签下的收藏列表
		//tid:需要查询的标签ID。
		public function loadFavoritesByTags(tid:String,count:int=50,page:int=1):void{
			callWeiboAPICommon(API.FAVORITE_BY_TAGS,processFavoritesArray,
				{tid:tid,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FAVORITE_LIST_BY_TAGS_RESULT,MicroBlogErrorEvent.LOAD_FAVORITE_LIST_BY_TAGS_ERROR);
		}
		//当前登录用户的收藏标签列表
		public function loadFavoritesTags(count:int=50,page:int=1):void{
			callWeiboAPICommon(API.FAVORITE_TAGS,processFavoritesTagsArray,
				{count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_FAVORITE_LIST_TAGS_RESULT,MicroBlogErrorEvent.LOAD_FAVORITE_LIST_TAGS_ERROR);
		}

		/*---------------------------- 收藏写入接口 ------------------------------------*/	
		//添加收藏
		public function addToFavorites(id:String):void{
			callWeiboAPICommon(API.ADD_FAVORITE,processFavorites,
				{id:id},URLRequestMethod.POST,
				MicroBlogEvent.ADD_TO_FAVORITES_RESULT,MicroBlogErrorEvent.ADD_TO_FAVORITES_ERROR);
		}
		//删除收藏
		public function removeFavorites(id:String):void{
			callWeiboAPICommon(API.DELETE_FAVORITE,processFavorites,
				{id:id},URLRequestMethod.POST,
				MicroBlogEvent.REMOVE_FROM_FAVORITES_RESULT,MicroBlogErrorEvent.REMOVE_FROM_FAVORITES_ERROR);
		}
		//批量删除收藏
		public function removeFavoritesBatch(ids:String):void{
			callWeiboAPICommon(API.DELETE_FAVORITE_BATCH,processGeneralApi,
				{ids:ids},URLRequestMethod.POST,
				MicroBlogEvent.REMOVE_FROM_FAVORITES_BATCH_RESULT,MicroBlogErrorEvent.REMOVE_FROM_FAVORITES_BATCH_ERROR);
		}
		//更新一条收藏的收藏标签
		//tags:需要更新的标签内容，必须做URLencode，用半角逗号分隔，最多不超过2条。
		public function updateFavoritesTags(id:String,tags:String):void{
			tags = encodeMsg(tags);
			callWeiboAPICommon(API.UPDATE_FAVORITE_TAGS,processFavorites,
				{id:id,tags:tags},URLRequestMethod.POST,
				MicroBlogEvent.UPDATE_FAVORITES_TAGS_RESULT,MicroBlogErrorEvent.UPDATE_FAVORITES_TAGS_ERROR);
		}
		//更新当前用户所有收藏下的指定标签
		//tid:需要更新的标签ID
		//tag:需要更新的标签内容，必须做URLencode。
		public function updateFavoritesTagsBatch(tid:String,tag:String):void{
			tag = encodeMsg(tag);
			callWeiboAPICommon(API.UPDATE_FAVORITE_TAGS_BATCH,processGeneralApi,
				{tid:tid,tag:tag},URLRequestMethod.POST,
				MicroBlogEvent.UPDATE_FAVORITES_TAGS_BATCH_RESULT,MicroBlogErrorEvent.UPDATE_FAVORITES_TAGS_BATCH_ERROR);
		}
		//删除当前用户所有收藏下的指定标签
		public function removeFavoritesTagsBatch(tid:String):void{
			callWeiboAPICommon(API.DELETE_FAVORITE_TAGS_BATCH,processGeneralApi,
				{tid:tid},URLRequestMethod.POST,
				MicroBlogEvent.REMOVE_FAVORITES_TAGS_BATCH_RESULT,MicroBlogErrorEvent.REMOVE_FAVORITES_TAGS_BATCH_ERROR);
		}		
		/*---------------------------- 话题读取接口 ------------------------------------*/
		//获取某人话题
		public function loadTrends(uid:String,count:int=50,page:int=1):void{
			callWeiboAPICommon(API.TRENDS,processTrends,
				{uid:uid,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_TRENDS_RESULT,MicroBlogErrorEvent.LOAD_TRENDS_ERROR);
		}
		//是否关注某话题
		public function isFollowTrends(trendName:String):void{
			callWeiboAPICommon(API.FOLLOW_TRENDS,processGeneralApi,
				{trend_name:trendName},URLRequestMethod.GET,
				MicroBlogEvent.FOLLOW_TRENDS_RESULT,MicroBlogErrorEvent.FOLLOW_TRENDS_ERROR);
		}		
		//返回最近一小时内的热门话题
		public function loadTrendsHourly():void{
			callWeiboAPICommon(API.TRENDS_HOURLY,processHotTrends,
				null,URLRequestMethod.GET,
				MicroBlogEvent.LOAD_TRENDS_HOURLY_RESULT,MicroBlogErrorEvent.LOAD_TRENDS_HOURLY_ERROR);
		}
		//返回最近一天内的热门话题
		public function loadTrendsDayly():void{
			callWeiboAPICommon(API.TRENDS_DAILY,processHotTrends,
				null,URLRequestMethod.GET,
				MicroBlogEvent.LOAD_TRENDS_DAYLY_RESULT,MicroBlogErrorEvent.LOAD_TRENDS_DAYLY_ERROR);
		}
		//返回最近一周内的热门话题
		public function loadTrendsWeekly():void{
			callWeiboAPICommon(API.TRENDS_WEEKLY,processHotTrends,
				null,URLRequestMethod.GET,
				MicroBlogEvent.LOAD_TRENDS_WEEKLY_RESULT,MicroBlogErrorEvent.LOAD_TRENDS_WEEKLY_ERROR);
		}		
		/*---------------------------- 话题写入接口 ------------------------------------*/	
		//关注某话题
		//返回Object topicid = "10689589"
		public function followTrends(trendName:String):void{
			trendName = encodeMsg(trendName);
			callWeiboAPICommon(API.FOLLOW_TRENDS,processGeneralApi,
				{trend_name:trendName},URLRequestMethod.POST,
				MicroBlogEvent.FOLLOW_TRENDS_RESULT,MicroBlogErrorEvent.FOLLOW_TRENDS_ERROR);
		}
		//取消关注某话题
		//返回Object result = true
		public function cancelTrends(trendId:String):void{
			callWeiboAPICommon(API.DELETE_TRENDS,processGeneralApi,
				{trend_id:trendId},URLRequestMethod.POST,
				MicroBlogEvent.CANCEL_TRENDS_RESULT,MicroBlogErrorEvent.CANCEL_TRENDS_ERROR);
		}
		/*---------------------------- 标签读取接口 ------------------------------------*/
		//获取用户标签
		public function loadTags(userId:String,count:int=50,page:int=1):void{
			callWeiboAPICommon(API.TAGS,processTags,
				{uid:userId,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_TAGS_RESULT,MicroBlogErrorEvent.LOAD_TAGS_ERROR);
		}
		//批量获取用户的标签列表
		public function loadTagsBatch(uids:String):void{
			callWeiboAPICommon(API.TAGS_BATCH,processTags,
				{uids:uids},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_TAGS_BATCH_RESULT,MicroBlogErrorEvent.LOAD_TAGS_BATCH_ERROR);
		}
		
		//获取系统推荐的标签列表
		//count:返回记录数，默认10，最大10。
		public function loadSuggestionsTags(count:int=10):void{
			callWeiboAPICommon(API.SUGGESTIONS_TAGS,processTags,
				{count:count},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_SUGGESTIONS_TAGS_RESULT,MicroBlogErrorEvent.LOAD_SUGGESTIONS_TAGS_ERROR);
		}
		/*---------------------------- 标签写入接口 ------------------------------------*/	
		//为当前登录用户添加新的用户标签
		//tags:要创建的一组标签，用半角逗号隔开，每个标签的长度不可超过7个汉字，14个半角字符。
		public function addTags(tags:String):void{
			tags = encodeMsg(tags);
			callWeiboAPICommon(API.ADD_TAGS,processGeneralApi,
				{tags:tags},URLRequestMethod.POST,
				MicroBlogEvent.ADD_TAGS_RESULT,MicroBlogErrorEvent.ADD_TAGS_ERROR);
		}
		//删除一个用户标签
		//Error 10020 : Request Api not found!,description:undefined
		public function deleteTags(tagId:String):void{
			callWeiboAPICommon(API.DELETE_TAGS,processGeneralApi,
				{tag_id:tagId},URLRequestMethod.POST,
				MicroBlogEvent.REMOVE_TAGS_RESULT,MicroBlogErrorEvent.REMOVE_TAGS_ERROR);
		}
		//批量删除用户标签
		//Error 10020 : Request Api not found!,description:undefined
		public function deleteTagsBatch(ids:String):void{
			callWeiboAPICommon(API.DELETE_TAGS_BATCH,processGeneralApi,
				{ids:ids},URLRequestMethod.POST,
				MicroBlogEvent.REMOVE_TAGS_BATCH_RESULT,MicroBlogErrorEvent.REMOVE_TAGS_BATCH_ERROR);
		}
		/*------------------------------ 搜索接口 -------------------------------------*/
		//@用户时的联想建议
		public function atUsers(qstr:String,type:String="0"):void{
			qstr = encodeMsg(qstr);//需要编码
			callWeiboAPICommon(API.AT_USERS,processAtUser,
				{q:qstr,type:type},URLRequestMethod.GET,
				MicroBlogEvent.AT_USERS_RESULT,MicroBlogErrorEvent.AT_USERS_ERROR);
		}
		/*---------------------------- 推荐读取接口 ------------------------------------*/
		//返回系统推荐的热门用户列表
		//推荐分类，返回某一类别的推荐用户，默认为default；如果不在以下分类中，返回空列表。default：人气关注、
		//ent：影视名星、music：音乐、fashion：时尚、literature：文学、business：商界、sports：体育、
		//health：健康、auto：汽车、house：房产、trip：旅行、stock：炒股、food：美食、fate：命理、
		//art：艺术、tech：科技、cartoon：动漫、games：游戏。
		public function loadHotUsers(category:String="default"):void{
			callWeiboAPICommon(API.HOT_USERS,processUsersBatch,
				{category:category},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_USERS_HOT_RESULT,MicroBlogErrorEvent.LOAD_USERS_HOT_ERROR);
		}
		//获取用户可能感兴趣的人
		//返回属性说明
		//返回值字段	字段类型	字段说明
		//uid		int64	推荐的用户UID
		//reason	object	推荐原因，有两种格式
		//tag		string	根据标签推荐，按内容推荐（格式1）
		//comp		string	根据公司推荐，按内容推荐（格式1）
		//scho		string	根据学校推荐，按内容推荐（格式1）
		//f			string	按粉丝关系推荐，按关系推荐（格式2）
		//h			string	按关注关系推荐，按关系推荐（格式2）
		//n			int		关联数量，按内容为具有相似内容的数量，按关系为具有相似关系人的数量		
		public function loadUsersMayInterested(count:int=10,page:int=1):void{
			callWeiboAPICommon(API.USERS_MAY_INTERESTED,processInterestedUser,
				{count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_USERS_MAY_INTERESTED_RESULT,MicroBlogErrorEvent.LOAD_USERS_MAY_INTERESTED_ERROR);
		}
		
		//根据一段微博正文推荐相关微博用户
		public function loadUsersByStatus(content:String,num:int=10):void{
			content = encodeMsg(content);
			callWeiboAPICommon(API.USERS_BY_STATUS,processGeneralApi,
				{content:content,num:num},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_USERS_BY_STATUS_RESULT,MicroBlogErrorEvent.LOAD_USERS_BY_STATUS_ERROR);
		}
		//获取微博精选推荐
		//type:微博精选分类，1：娱乐、2：搞笑、3：美女、4：视频、5：星座、6：各种萌、7：时尚、8：名车、9：美食、10：音乐。
		//isPic:是否返回图片精选微博，0：全部、1：图片微博。
		public function loadHotStatus(type:int=1,isPic:int=0,count:int=20,page:int=1):void{
			callWeiboAPICommon(API.STATUSES_HOT,processStatusHotArray,
				{type:type,is_pic:isPic,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_HOT_STATUS_RESULT,MicroBlogErrorEvent.LOAD_HOT_STATUS_ERROR);
		}	
		//主Feed微博按兴趣推荐排序
		//section:排序时间段，距现在n秒内的微博参加排序，最长支持24小时。
		//Error 10001 : system error!,description:undefined
		public function loadStatusReorder(section:int=10,count:int=50,page:int=1):void{
			callWeiboAPICommon(API.STATUSES_REORDER,processGeneralApi,
				{section:section,count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_STATUS_REORDER_RESULT,MicroBlogErrorEvent.LOAD_STATUS_REORDER_ERROR);
		}
		//返回系统推荐的热门收藏
		public function loadHotFavorites(count:int=50,page:int=1):void{
			callWeiboAPICommon(API.HOT_FAVORITES,processGeneralApi,
				{count:count,page:page},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_HOT_FAVORITES_RESULT,MicroBlogErrorEvent.LOAD_HOT_FAVORITES_ERROR);
		}
		/*---------------------------- 推荐写入接口 ------------------------------------*/	
		//把某人标识为不感兴趣的人
		public function markNotInterested(uid:String):void{
			callWeiboAPICommon(API.USERS_NOT_INTERESTED,processGeneralApi,
				{uid:uid},URLRequestMethod.POST,
				MicroBlogEvent.MARK_NOT_INTERESTED_RESULT,MicroBlogErrorEvent.MARK_NOT_INTERESTED_ERROR);
		}
		/*------------------------------- 提醒接口--------------------------------------*/
		//获取用户各种消息未读数
		public function loadUnreadCount(userId:String):void{
			callWeiboAPICommon(API.UNREAD_COUNT,processUnreadCount,
				{uid:userId},URLRequestMethod.GET,
				MicroBlogEvent.UNREAD_COUNT_RESULT,MicroBlogErrorEvent.UNREAD_COUNT_ERROR);
		}
		
		/*------------------------------- 公共服务--------------------------------------*/
		//通过地址编码获取地址名称
		public function loadCode2Loaction(codes:String):void{
			callWeiboAPICommon(API.CODE_TO_LOCATION,processGeneralApi,
				{codes:codes},URLRequestMethod.GET,
				MicroBlogEvent.LOAD_CODE_2_LOCATION_RESULT,MicroBlogErrorEvent.LOAD_CODE_2_LOCATION_ERROR);
		}	
		//获取城市列表
		//capital:城市的首字母，a-z，可为空代表返回全部，默认为全部
		//language:返回的语言版本，zh-cn：简体中文、zh-tw：繁体中文、english：英文，默认为zh-cn。
		public function getCity(province:String,capital:String=null,language:String="zh-cn"):void{
			var param:Object = new Object();
			if(capital){
				param.capital = capital;
			}
			param.province = province;
			param.language = language;			
			callWeiboAPICommon(API.GET_CITY,processLocation,
				param,URLRequestMethod.GET,
				MicroBlogEvent.GET_CITY_RESULT,MicroBlogErrorEvent.GET_CITY_ERROR);
		}
		//获取省份列表
		//capital:城市的首字母，a-z，可为空代表返回全部，默认为全部
		//language:返回的语言版本，zh-cn：简体中文、zh-tw：繁体中文、english：英文，默认为zh-cn。
		public function getProvince(country:String,capital:String=null,language:String="zh-cn"):void{
			var param:Object = new Object();
			if(capital){
				param.capital = capital;
			}
			param.country = country;
			param.language = language;			
			callWeiboAPICommon(API.GET_PROVINCE,processLocation,
				param,URLRequestMethod.GET,
				MicroBlogEvent.GET_PROVINCE_RESULT,MicroBlogErrorEvent.GET_PROVINCE_ERROR);
		}
		//获取省份列表
		//capital:城市的首字母，a-z，可为空代表返回全部，默认为全部
		//language:返回的语言版本，zh-cn：简体中文、zh-tw：繁体中文、english：英文，默认为zh-cn。
		public function getCountry(capital:String=null,language:String="zh-cn"):void{
			var param:Object = new Object();
			if(capital){
				param.capital = capital;
			}
			param.language = language;
			
			callWeiboAPICommon(API.GET_COUNTRY,processLocation,
				param,URLRequestMethod.GET,
				MicroBlogEvent.GET_COUNTRY_RESULT,MicroBlogErrorEvent.GET_COUNTRY_ERROR);
		}
		/*------------------------------- 地理信息--------------------------------------*/
		//根据关键词查询公交线路信息
		//q:查询的关键词，必须进行URLencode。
		//city:城市代码，默认为北京搜索。
		//Error 21903 : Returns no data,description:undefined
		public function getBusLine(q:String,city:String="0010",count:int=50,page:int=1):void{
			q = encodeMsg(q);
			callWeiboAPICommon(API.BUS_LINE,processGeneralApi,
				{q:q,city:city,page:page,count:count},URLRequestMethod.GET,
				MicroBlogEvent.GET_BUS_LINE_RESULT,MicroBlogErrorEvent.GET_BUS_LINE_ERROR);
		}
		
		/*------------------------------- 通用接口--------------------------------------*/
		public function callWeiboAPI(uri:String, params:Object = null, method:String = "GET", resultEventType:String = "callWeiboApiResult", errorEventType:String = "callWeiboApiError"):void
		{
			addProcessor(uri, processGeneralApi, resultEventType, errorEventType);
			if (params == null) var params:Object = { };
			if(_isSecureDomain){
				executeRequest(uri, getMicroBlogRequest(API.API_BASE_URL + uri + ".json", params, method));
			}else{				
				executeRequest(uri, getMicroBlogRequest(_proxyURI + "?uri=" + uri + "&method=" + method, params, URLRequestMethod.POST));
			}
		}
		
		//通用AIP调用方法，与callWeiboAPI不同的地方是添加处理方法参数
		protected function callWeiboAPICommon(uri:String, dataProcess:Function,params:Object = null, method:String = "GET", resultEventType:String = "callWeiboApiResult", errorEventType:String = "callWeiboApiError"):void{
			addProcessor(uri, dataProcess, resultEventType, errorEventType);
			if (params == null) var params:Object = { };
			if(_isSecureDomain){
				executeRequest(uri, getMicroBlogRequest(API.API_BASE_URL + uri + ".json", params, method));
			}else{				
				executeRequest(uri, getMicroBlogRequest(_proxyURI + "?uri=" + uri + "&method=" + method, params, URLRequestMethod.POST));
			}
		}
		
		
		///////////////////////////////////
		// getter/setters
		///////////////////////////////////
		/**
		 * consumerKey是一个只写属性，用于验证客户端的合法性，
		 * 必须在调用login之前将其设置为合适值.
		 * @param value
		 * 
		 */		
		public function set consumerKey(value:String):void
		{
			_consumerKey = value;
			_source = value;
		}
		
		/**
		 * consumerSecret是一个只写属性，用于和consumerKey一起验证客户端的合法性，
		 * 必须在调用login之前将其设置为合适值.
		 * @param value
		 * 
		 */		
		public function set consumerSecret(value:String):void
		{
			_consumerSecret = value;
		}
		
		public function get access_token():String{ return _access_token; }
		public function set access_token(value:String):void
		{
			_access_token = value;
		}
		
		public function get expires_in():String{ return _expires_in; }
		public function set expires_in(value:String):void
		{
			_expires_in = value;
		}
		
		public function get refresh_token():String{ return _refresh_token; }
		public function set refresh_token(value:String):void
		{
			_refresh_token = value;
		}
		
		/**
		 * source是标识客户端来源.必须设置为新浪认证的应用程序id 
		 * @return 
		 * 
		 */		
		public function get source():String { return _source; }
		public function set source(value:String):void
		{
			_source = value;
			_consumerKey = value;
		}
		
		public function get pin():String { return _pin; }
		public function set pin(value:String):void
		{
			_pin = value;
		}
		
		/**
		 * 微博秀的特殊需求创建，用于获取用户信息的标识，使用用户帐号的创建时间编码获得 
		 * 微博特殊应用的认证标识，例如微博秀，
		 * @return 
		 * 
		 */		
		public function get verifier():String { return _verifier; }
		public function set verifier(value:String):void
		{
			_verifier = value;
		}
		
		
		public function get proxyURI():String{ return _proxyURI; }
		public function set proxyURI(value:String):void
		{
			_proxyURI = value;
			_isSecureDomain = (_proxyURI == "");
			trace(">>" + _isSecureDomain + "::" + _proxyURI);
		}
		
		///////////////////////////////////
		// Data Process Function
		///////////////////////////////////		
		//默认数据处理函数
		private function processGeneralApi(value:Object):Object
		{
			return value;
		}
		//处理用户
		protected function processUser(value:Object):MicroBlogUser{
			return new MicroBlogUser(value);
		}
		//处理用户列表
		protected function processUserArray(value:Object):MicroBlogListVO{
			var vo:MicroBlogListVO = new MicroBlogListVO();
			
			var microBlogUser:MicroBlogUser;
			var userArray:Array=[];
			for each (var user:Object in value.users)
			{
				microBlogUser=new MicroBlogUser(user);
				userArray.push(microBlogUser);
			}
			
			vo.hasvisible = value.hasvisible;
			vo.next_cursor = value.next_cursor;
			vo.previous_cursor = value.previous_cursor;
			vo.total_number = value.total_number;
			vo.list = userArray;
			return vo;
		}
		//处理微博
		protected function processStatus(value:Object):MicroBlogStatus
		{
			return new MicroBlogStatus(value);
		}
		//处理微博列表
		private function processStatusArray(value:Object):MicroBlogListVO
		{
			var vo:MicroBlogListVO = new MicroBlogListVO();
			
			var microBlogStatus:MicroBlogStatus;
			var statusArray:Array=[];
			for each (var status:Object in value.statuses)
			{
				microBlogStatus=new MicroBlogStatus(status);
				statusArray.push(microBlogStatus);
			}
			
			vo.hasvisible = value.hasvisible;
			vo.next_cursor = value.next_cursor;
			vo.previous_cursor = value.previous_cursor;
			vo.total_number = value.total_number;
			vo.list = statusArray;
			return vo;
		}
		
		//处理评论
		protected function processComment(value:Object):MicroBlogComment{
			return new MicroBlogComment(value);
		}
		
		//处理评论列表
		private function processCommentArray(value:Object):MicroBlogListVO{
			var vo:MicroBlogListVO = new MicroBlogListVO();
			var comments:Array = value.comments;
			var microBlogComment:MicroBlogComment;
			var commentArray:Array=[];
			for each(var comment:Object in comments)
			{
				microBlogComment=new MicroBlogComment(comment);
				commentArray.push(microBlogComment);
			}
			
			vo.hasvisible = value.hasvisible;
			vo.next_cursor = value.next_cursor;
			vo.previous_cursor = value.previous_cursor;
			vo.total_number = value.total_number;
			vo.list = commentArray;
			return vo;
		}
		//处理收藏列表
		protected function processFavoritesArray(value:Object):Array{
			var result:Array = [];
			for each(var favorites:Object in value.favorites){
				result.push(new MicroBlogFavorites(favorites));
			}
			return result;
		}
		//处理收藏标签列表
		protected function processFavoritesTagsArray(value:Object):Array{
			var result:Array = [];
			for each(var tag:Object in value.tags){
				result.push(new MicroBlogFavoritesTag(tag));
			}
			return result;
		}
		
		//处理收藏
		protected function processFavorites(value:Object):MicroBlogFavorites{
			return new MicroBlogFavorites(value);
		}
		//处理未读消息
		private function processUnreadCount(value:Object):MicroBlogUnread{
			return new MicroBlogUnread(value);
		}
		//处理各种未读消息数
		private function processStatusCount(value:Object):Array{
			var result:Array = [];
			for each(var count:Object in value){
				result.push(new MicroBlogCount(count));
			}
			return result;
		}
		//批量处理用户
		private function processUsersBatch(value:Object):Array{
			var result:Array = [];
			for each(var user:Object in value){
				result.push(new MicroBlogUser(user));
			}
			return result;
		}
		//批量处理评论
		private function processCommentsBatch(value:Object):Array{
			var result:Array = [];
			for each(var comment:Object in value){
				result.push(new MicroBlogComment(comment));
			}
			return result;
		}
		
		//表情处理
		private function processEmotions(value:Object):Array{
			var list:Array = new Array();
			var categorys:Array = new Array();
			for each(var emotion:Object in value){
				list.push(new MicroBlogEmotion(emotion));
				//获取分类，放到列表里
				if(categorys.indexOf(emotion.category)==-1){
					categorys.push(emotion.category);
				}
			}
			//根据类别来分一下类
			var result:Array = new Array();
			for each(var category:String in categorys){
				if(!category) continue;
				
				var tmp:Array = new Array();
				for each(var em:MicroBlogEmotion in list){
					if(category == em.category){
						tmp.push(em);
					}
				}
				//分类放到结果里
				var item:Object = new Object();
				item.catetory = category;
				item.list = tmp;
				result.push(item);
			}

			
			return result;
		}
		//处理关系
		protected function processRelation(value:Object):MicroBlogUsersRelationship{
			return new MicroBlogUsersRelationship(value);
		}
		//处理API调用频率
		protected function processRateLimit(value:Object):MicroBlogRateLimit{
			return new MicroBlogRateLimit(value);
		}
		
		//  [8] (Object)#9
		//    813 = "交互设计"
		//    weight = "2655"
		//  [9] (Object)#10
		//    391 = "java"
		//    weight = "3875"		
		//处理微博标签
		protected function processTags(value:Object):Array{
			var result:Array = [];
			for each(var item:Object in value){
				var vo:Object = new Object();
				//注意下面这个循环没有用for each，数据示例见上面，为的是取id
				for (var field:Object in item){
					vo.id = field;
					vo.name = item[field];
					break;//取出ID后就跳出来
				}
				vo.weight = item.weight;
				result.push(new MicroBlogTag(vo));
			} 
			return result;
		}
		//处理搜索时@用户列表
		protected function processAtUser(value:Object):Array{
			var result:Array = [];
			for each(var item:Object in value){
				result.push(new MicroBlogAtUser(item));
			}
			return result;
		}
		//处理感兴趣的人
		protected function processInterestedUser(value:Object):Array{
			var result:Array = [];
			for each(var item:Object in value){
				result.push(new MicroBlogInterestedUser(item));
			}
			return result;
		}
		//处理热门微博
		protected function processStatusHotArray(value:Object):Array{
			var result:Array = [];
			for each(var item:Object in value.statuses){
				result.push(new MicroBlogHotStatuses(item));
			}
			return result;
		}
		//处理地址，国家，省份，城市，
		protected function processLocation(value:Object):Array{
			var result:Array = [];
			for each(var item:Object in value){
				//注意此处没有用for each循环
				for(var id:String in item){
					var loc:Object = new Object();
					loc.id = id;
					loc.name = item[id];
					result.push(new MicroBlogLocation(loc));					
				}
			}
			return result;
		}
		//处理话题列表
		protected function processTrends(value:Object):Array{
			var result:Array = [];
			for each(var item:Object in value){
				result.push(new MicroBlogTrends(item));
			}
			return result;
		}
		
		//处理一小时、一天、一周内的热门话题
		protected function processHotTrends(value:Object):Array{
			var result:Array = [];
			for each(var list:Array in value.trends){
				for each(var trend:Object in list){
					result.push(new MicroBlogHotTrends(trend));
				}
			}
			return result;
		}
		///////////////////////////////////
		// Util Function
		///////////////////////////////////	
		protected function addProcessor(name:String, dataProcess:Function, resultEventType:String, errorEventType:String):void
		{
			if (null == serviceLoader[name])
			{
				var loader:URLLoader=new URLLoader();
				loader.addEventListener(Event.COMPLETE, loader_onComplete);
				loader.addEventListener(IOErrorEvent.IO_ERROR, loader_onError);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loader_onSecurityError);
				serviceLoader[name]=loader;
				loaderMap[loader]={dataFunc: dataProcess, resultEvent: resultEventType, errorEvent: errorEventType};
			}
		}
		
		protected function getMicroBlogRequest(url:String, params:Object = null, requestMethod:String="GET"):URLRequest
		{
			var req:URLRequest;		
			if ( null == params ) params = { };		
			params.source = this._consumerKey;		
			if(access_token != "") params.access_token = access_token;
			if(requestMethod == URLRequestMethod.GET){
				url+=makeGETParamString(params);
				req = new URLRequest(url)
			}else if(requestMethod == URLRequestMethod.POST){
				req = new URLRequest(url)
				var val:URLVariables = new URLVariables();
				for (var key:* in params)
				{
					val[key] = params[key];
				}
				req.data = val;
			}
			
			req.method=requestMethod;
			return req;
		}
		
		protected function executeRequest(name:String, req:URLRequest):void
		{
			var urlLoader:URLLoader = serviceLoader[name] as URLLoader;
			urlLoader.load(req);
		}
		
		protected function makeGETParamString(parameters:Object):String
		{
			var paramStr:String=makeParamsToUrlString(parameters);
			if (paramStr.length > 0) paramStr="?" + paramStr;
			return paramStr;
		}
		
		protected function makeParamsToUrlString(params:Object):String
		{
			var retParams:Array=[];			
			for (var param:String in params)
			{
				retParams.push(param + "=" + params[param].toString());
			}
			retParams.sort();
			return retParams.join("&");
		}
		
		protected function encodeMsg(status:String):String
		{
			var source:String = status;
			var pattern1:RegExp = new RegExp('^[ ]+|[ ]+$', 'g');
			source = source.replace(pattern1, '');		
			var pattern2:RegExp = new RegExp('[ \n\t\r]', 'g');
			source = source.replace(pattern2, ' ');				
			var pattern3:RegExp = /( )+/g;
			source = source.replace(pattern3, ' ');			
			return StringEncoders.urlEncodeSpecial(source);
		}
		
		protected function makeMultipartPostData(boundary:String, imgFieldName:String, filename:String, imgData:ByteArray, params:Object):Object
		{
			var req:URLRequest=new URLRequest();
			var postData:ByteArray=new ByteArray();
			postData.endian=Endian.BIG_ENDIAN;
			var value:String;
			if (params)
			{
				for (var name:String in params)
				{
					boundaryPostData(postData, boundary);
					addLineBreak(postData);
					postData.writeUTFBytes(CONTENT_DISPOSITION_BASIC.replace("$name", name));
					addLineBreak(postData);
					addLineBreak(postData);
					postData.writeUTFBytes(params[name]);
					addLineBreak(postData);
				}
			}
			
			boundaryPostData(postData, boundary);
			addLineBreak(postData);
			postData.writeUTFBytes(CONTENT_DISPOSITION_BASIC.replace("$name", imgFieldName) + '; filename="' + filename + '"');
			addLineBreak(postData);
			postData.writeUTFBytes(CONTENT_TYPE_JPEG);
			addLineBreak(postData);
			addLineBreak(postData);
			postData.writeBytes(imgData, 0, imgData.length);
			addLineBreak(postData);
			
			boundaryPostData(postData, boundary);
			addDoubleDash(postData);
			
			postData.position=0;
			return postData;
		}
		
		protected function boundaryPostData(data:ByteArray, boundary:String):void
		{
			var len:int=boundary.length;
			addDoubleDash(data);
			for (var i:int=0; i < len; ++i)
			{
				data.writeByte(boundary.charCodeAt(i));
			}
		}
		
		protected function addDoubleDash(data:ByteArray):void
		{
			data.writeShort(0x2d2d);
		}
		
		protected function addLineBreak(data:ByteArray):void
		{
			data.writeShort(0x0d0a);
		}
		
		protected function makeBoundary():String
		{
			var boundary:String="";
			for (var i:int=0; i < 13; i++)
			{
				boundary+=String.fromCharCode(int(97 + Math.random() * 25));
			}
			boundary="---------------------------" + boundary;
			return boundary;
		}
		
	}
}